package com.body.park.gateway.utils;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.body.park.gateway.entity.User;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

import java.util.Map;

/**
 * @Author chaox-wu
 * @Date 2022/12/2
 * @Description:
 */
public class JwtUtils {

    /**
     * 获取jwt令牌用户信息
     *
     * @param token
     * @return
     */
    public static User getUserJwtFromToken(String token) {
        //直接根据token拿到用户的信息啊
        Map jwtClaims = null;
        //解析jwt
        Jwt decode = JwtHelper.decode(token);
        //得到 jwt中的用户信息
        String claims = decode.getClaims();
        //将jwt转为Map
        jwtClaims = JSONUtil.toBean(claims, Map.class);
        User userJwt = new User();
        userJwt.setId(Long.parseLong(String.valueOf(jwtClaims.get("id"))));
        userJwt.setName(String.valueOf(jwtClaims.get("username")));
        return userJwt;
    }
}
